TOOL.Category = "Turret Weaons"
TOOL.Name = "Laser Turret"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.ent = {} 
TOOL.ClientConVar["Power"] = "5"
cleanup.Register( "laserturret" )

if CLIENT then
   language.Add ("Tool_laserturret_name", "Laser Turret")
   language.Add ("Tool_laserturret_desc", "A customizable Laser Turret.")
   language.Add ("Tool_laserturret_0", "Primary: Spawn a Laser Turret")
   language.Add ("Undone_laserturret", "Laser Turret undone.")
end



function TOOL:LeftClick( trace )
	if (CLIENT) then return true end
	local ply = self:GetOwner()

	if ( !trace.Hit ) then return end
	local Ang = (trace.HitNormal:Angle() + Angle(90,0,0))
		local Pos = trace.HitPos + trace.HitNormal* 8
	if ( SERVER and !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end

	   local Power = self:GetClientNumber("power")

	local Weapon = MakeLaser(ply, Pos, Ang, Power)
	
	local phys = Weapon:GetPhysicsObject()  	
	if (phys:IsValid()) then  		
		local weld = constraint.Weld(Weapon, trace.Entity, 0, trace.PhysicsBone, 0)
		local nocollide = constraint.NoCollide(Weapon, trace.Entity, 0, trace.PhysicsBone)
		undo.Create("laserturret")
		undo.AddEntity( Weapon )
		undo.AddEntity( weld )
		undo.AddEntity( nocollide )
		undo.SetPlayer( ply )
	undo.Finish()
	end 
	
   return true
end

function TOOL:RightClick( trace )
	if (CLIENT) then return true end
	local ply = self:GetOwner()

	if ( !trace.Hit ) then return end
	local Ang = (trace.HitNormal:Angle() + Angle(90,0,0))
		local Pos = trace.HitPos + trace.HitNormal* 8
	if ( SERVER and !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end

	   local Power = self:GetClientNumber("power")

	local Weapon = MakeLaser(ply, Pos, Ang, Power)
	
	
	undo.Create("laserturret")
		undo.AddEntity( Weapon )
		undo.SetPlayer( ply )
	undo.Finish()
	
   return true
end



if (SERVER) then

	 function MakeLaser(pl, Pos, Ang, Pow)
		
		
	
	local turretlaser = ents.Create("turretlaser")
    turretlaser:SetPos(Pos)
	turretlaser:SetAngles( Ang)
	turretlaser:Spawn()
    turretlaser:Activate()
    turretlaser:Setup(Pow)
	
	local ttable = {
					Pow = Pow;
						}
		table.Merge(turretlaser:GetTable(), ttable )
	
	return turretlaser
	end
duplicator.RegisterEntityClass("turretlaser",  MakeLaser, "Pos", "Ang", "Pow", "frozen")
end

if CLIENT then
function TOOL.BuildCPanel(panel)
   
   panel:AddControl("Header", {Text = "#Tool_laserturret_name", Description = "#Tool_laserturret_desc"})

   panel:AddControl("Slider", {
      Label = "Power",
      Type = "Integer",
      Min = "5",
      Max = "100",
      Command = "laserturret_Power"})

end 
end 